//
// Created by root on 2020/4/21.
//

#ifndef HEATBEATSERVER_USERMGR_H
#define HEATBEATSERVER_USERMGR_H

#include <atomic>
#include <mutex>
#include <queue>
#include <string>
#include <unordered_map>
#include <vector>

#include <muduo/base/Singleton.h>
#include <muduo/base/Thread.h>

#include "User.h"

class CUserMgr {
public:
    CUserMgr();
    virtual ~CUserMgr();

    void Insert(const CUser &_oUser);
    /**
     *
     * @param _sId
     * @return true : 删除成功 false: 删除失败
     */
    bool Delete(const std::string &_sId);
    CUser GetUser(const std::string &_sId);
    std::vector<std::string> GetAllUserName();

    void CheckRegular();
    void UpdateRegular(const std::string &_sName);

    void Send(const std::string &_sRecieveId, uint64_t _iPacketId, const std::string &_sMessage);
    bool IsValid(const std::string &_sConnId);

private:
    /**
     *  发送线程方法
     */
    void Run();

private:
    std::mutex mutexRegistry;   ///< 注册表锁
    std::unordered_map<std::string, CUser> m_hashRegistry;   ///< 注册表
    std::unordered_map<std::string, bool> m_hashId2Time;    ///<  id —— 是否已经接受过心跳

    std::mutex m_mutexQueue; ///< 用于发送数据队列锁 ----- m_queueSend
    std::queue<std::pair<std::string, std::string>> m_queueSend;    ///< 发送队列

private:
    muduo::Thread *m_pSendMsgThd = nullptr;   ///< 发送消息线程
    std::atomic_bool m_bExitThd = false;
};

using gUserMgr = muduo::Singleton<CUserMgr>;

#endif //HEATBEATSERVER_USERMGR_H
